<template>
  <el-container>
    <el-header v-if="titleShow" height="36px">
      <header-title :title="headerTitle" />
    </el-header>
    <div style="padding: 15px 25px 0px;width: 100%;">
      <!-- 基本信息 -->
      <TCollapse title="项目基础信息" class="newSty">
        <iframe ref="basinRef" style="width:100%;" scrolling="no" frameborder="0" :src="basinInfoSrc" />
      </TCollapse>
      <!-- 项目专属信息 -->
      <TCollapse title="项目专属信息">
        <iframe ref="proprietaryInfoRef" style="width:100%;" scrolling="no" frameborder="0" :src="proprietaryInfoSrc" />
      </TCollapse>
      <!-- 竣工决算信息 -->
      <TCollapse title="竣工决算信息">
        <beCompletedDetail ref="projectProprietary" :select-list="selectList" :form-val="Proprietarylist" :url-list="urlList" :lc-list="lcList" :prj-id="prjId" />
      </TCollapse>
      <!-- 附件 -->
      <TCollapse title="附件">
        <iframe ref="myIframeFjRef" style="width:100%;" frameborder="0" scrolling="no" :src="fuJianSrc" />
      </TCollapse>
      <!-- 项目审批信息 -->
      <TCollapse title="项目审批信息">
        <iframe ref="myIframe4" :src="spIframeSrc" style="width:100%;" scrolling="no" frameborder="0" />
      </TCollapse>
      <FooterButton :button-disable="buttonDisable" @handleClose="handleClose" @handleNext="handleNext" @handleBack="handleBack" />
      <!-- // 下一步 && 回退 -->
      <next-page
        v-if="nextPageVisible"
        ref="nextPage"
        :visible.sync="nextPageVisible"
        :activity-inst-id="workFlowData.activityInstID"
        :process-inst-id="workFlowData.processInstID"
        :activity-def-id="workFlowData.activityDefID"
        :process-def-name="workFlowData.processDefName"
        @doNextEntity="nextPageRes"
      />
      <Back-page
        v-if="backPageVisible"
        ref="backPage"
        :visible.sync="backPageVisible"
        :process-inst-id="workFlowData.processInstID"
        :act-inset-id="workFlowData.actInsetId"
        @doReturn="backPageRes"
      />
    </div>
  </el-container>
</template>

<script>
import FooterButton from '@/components/footer/details'
import HeaderTitle from '@/components/basic/HeaderTitle'
import beCompletedDetail from '@/views/actualBudget/business/BeCompletedDetail'

import NextPage from '@/components/nextPerson/NextPage'
import BackPage from '@/components/nextPerson/BackPage'
import TCollapse from '@/components/basic/TCollapse.vue'

// import * as Common from '@/api/common'
import {
  getWFWorkItem,
  queryTFinInfoNew,
  getPrjDetail,
  isRevocationAndAdjNew,
  finalNextFlowNew,
  getIsPushNew,
  confirmationOfArrivalNew,
  isSettleAccountsFinishNew,
  checkValidNew
} from '@/api/actualBudget'
import { clonePage } from '@/utils'

export default {
    name: 'AcceptMangeDetail',
    components: {
        TCollapse,
        FooterButton,
        HeaderTitle,
        beCompletedDetail,
        NextPage,
        BackPage
    },
    data() {
        return {
            junNanUrl: process.env.VUE_APP_JUNNAN_IFRAME_URL,
            fileUrl: process.env.VUE_APP_ZHONGRUAN_URL,
            nextPageVisible: false, // 下一步
            backPageVisible: false, // 回退
            workFlowData: {
              activityInstID: null,
              processInstID: null, // 下一步 && 回退
              activityDefID: null,
              actInsetId: null, // 下一步 && 回退
              processDefName: ''
            },
            titleShow: true, // 默认展示头部信息,综合查询时候不展示
            headerTitle: '',
            basinInfoSrc: '',
            proprietaryInfoSrc: '',
            spIframeSrc: '',
            fuJianSrc: '',
            // entre: '',
            selectList: {},
            detailData: {},
            Proprietarylist: {},
            buttonDisable: ['doNext', 'close'],
            newCollapseList: {},
            refprjBaDetail: {}, // ifarm获取基本信息
            refbeClDetail: {}, // 获取决算竣工信息
            basicList: {}, // 基本信息
            prjId: '',
            lcList: '',
            getTowerTypeAByPrjIdList: {},
            getRoomTypeBByPrjIdList: {},
            basicInfo: {},
            proprietaryInfo: {},
            urlList: {},
            processInstId: '',
            btnConfig: 'A' // 默认传A .综合查询传B
        }
    },
    async created() {
      var urlVal = window.location.href
      this.urlList = this.GetRequest(urlVal)
      if (this.urlList.workItemId) {
        const { data } = await getWFWorkItem({ workItemId: this.urlList.workItemId })
        this.lcList = data // 获取流程参数信息
        this.prjId = data.bizObject.prjId
      } else {
        this.prjId = this.urlList.prjId
        this.btnConfig = 'B'
      }

      if (this.urlList.processInstId) {
        this.processInstId = this.urlList.processInstId
      } else {
        this.processInstId = this.lcList.processInstID
      }
      this.ifarmSrcPram()
      this.setData() // 获取竣工决算表信息
      // this.getSelectData() // 字典
      // 初始化判断 是否可操作
      if (this.urlList.type === 'done' || this.urlList.type === '1') {
        this.buttonDisable = []
        this.btnConfig = 'B'
        this.titleShow = false
      }

      // 判断是否展示退回按钮
      if (this.urlList.type !== 'done' && (this.lcList.activityDefID === 'info_it_invest_js_02_02' || this.lcList.activityDefID === 'info_it_fee_js02')) {
        this.buttonDisable = ['doNext', 'back', 'close']
      }
    },
    async mounted() {
      this.getList() // 获取基本信息
    },
    methods: {
        // 获取基本信息 专属信息 站址信息
        async getList() {
            window.addEventListener('message', (event) => {
              const base_url = ''
              if (event.origin === base_url) {
                return
              }
              // 基本信息高度
              if (event.data.type === 'basicHeight') {
                this.$refs.basinRef.style.height = event.data.data + 'px'
              }
              // 专属信息高度
              if (event.data.type === 'proiprHeight') {
                this.$refs.proprietaryInfoRef.style.height = event.data.data + 'px'
              }
              if (event.data.type === 'basicInfo') {
                  this.basicInfo = JSON.parse(event.data.data)
                  // console.log('基本信息')
              }
              if (event.data.type === 'proprietaryInfo') {
                this.proprietaryInfo = JSON.parse(event.data.data)
                // console.log('专属信息')
              }
              if (event.data.type === 'siteInfo') {
                  // console.log('站址信息')
              }
              if (event.data.type === 'attachment') {
                this.$refs.myIframeFjRef.style.height = event.data.height + 'px'
                // console.log('附件高度')
              }
              if (event.data.type === 'commentHeight') {
                console.log('项目审批信息', event.data)
                this.$refs.myIframe4.style.height = event.data.data
              }
            })
        },
        // 获取竣工决算表基本信息
        async setData() {
            const queryTFinInfo = await queryTFinInfoNew({ prjId: this.prjId })
            if (queryTFinInfo.code === '200') {
                this.Proprietarylist = queryTFinInfo.data
            }
        },
        // 获取url 携带参数
        GetRequest(url) {
            var theRequest = {}
            if (url.indexOf('?') !== -1) {
                var str = url.substr(1)
                var strs = str.split('?')
                var strsList = strs[1].split('&')
                for (var i = 0; i < strsList.length; i++) {
                    theRequest[strsList[i].split('=')[0]] = strsList[i].split('=')[1]
                }
            }
            return theRequest
        },

        // 获取下拉框数据字典
        // async getSelectData() {
        //     const arr = ['PROJ_TYPE', 'SECONDARY_TYPE', 'BUILD_MODES', 'PURCHASE_METHOD']
        //     for (const i in arr) {
        //         const res = await Common.getDropdownData(arr[i])
        //         this.$set(this.selectList, arr[i], res.data)
        //     }
        // },

        // ifarm src 传参
        async ifarmSrcPram() {
            await getPrjDetail({ prjId: this.prjId }).then(res => {
                this.headerTitle = res.data.prjName
                this.basicList = res.data // 获取基本信息
            })
            if (this.urlList.type !== 'done' && (this.basicList.secondaryType === '14' && this.lcList.activityDefID === 'info_it_invest_js_02_01')) {
                this.$refs.projectProprietary.AssetAssemblyShow = true
            }
            if (this.lcList.activityDefID === 'info_it_invest_js_02_02') {
                this.$refs.projectProprietary.AttachmentPassShow = true
            }
            // 后续需要区分 室分类项目室分类型
            // if (this.basicList.prjType === 'A') {
            //   const getTowerTypeAByPrjId = await Axios.getTowerTypeAByPrjId({ prjId: this.prjId })
            //   if (getTowerTypeAByPrjId.code === '200') {
            //     this.getTowerTypeAByPrjIdList = getTowerTypeAByPrjId.data // 获取铁塔类项目铁塔种类
            //   }
            // }
            // if (this.basicList.prjType === 'B') {
            //   const getRoomTypeBByPrjId = await Axios.getRoomTypeBByPrjId({ prjId: this.prjId })
            //   if (getRoomTypeBByPrjId.code === '200') {
            //     this.getRoomTypeBByPrjIdList = getRoomTypeBByPrjId.data // 获取室分类项目室分类型
            //   }
            // }

            var iframeParams = {
              prjType: this.basicList.prjType,
              nodeId: this.lcList.activityDefID, // activityDefID 流程节点ID
              buildModes: this.basicList.buildModes,
              orgId: this.basicList.orgId,
              towerType: '0',
              roomType: '0',
              prjId: this.basicList.prjId,
              projectId:this.prjId,
              prjStage: 'G',
              fileSupplierCode: '', // 供应商接口
              isChange: '0', // 默认传0
              operateType: '1', // 默认传1
              btnConfig: this.btnConfig// 默认传A .综合查询传B
            }

            // 基本信息
            this.basinInfoSrc = `${this.junNanUrl}design/basicInfo?prjId=${this.prjId}`
            // 项目专属信息
            this.proprietaryInfoSrc = `${this.junNanUrl}design/proprietaryInfo?prjId=${this.prjId}&processInstId=${this.processInstId}`
           // 附件信息
           this.fuJianSrc = `${this.fileUrl}attachmentInfo?prjType=${iframeParams.prjType}&nodeId=${iframeParams.nodeId}&buildModes=${iframeParams.buildModes}&towerType=${iframeParams.towerType}&roomType=${iframeParams.roomType}&prjId=${iframeParams.prjId}&prjStage=${iframeParams.prjStage}&fileSupplierCode=${iframeParams.fileSupplierCode}&isChange=${iframeParams.isChange}&operateSystem=${iframeParams.operateSystem}&operateType=${iframeParams.operateType}&btnConfig=${iframeParams.btnConfig}&orgId=${iframeParams.orgId}&projectId=${iframeParams.projectId}`
            // 项目关闭信息
            this.spIframeSrc = `${this.junNanUrl}workflow/taskDetail/handleOnlyRecord?prjId=${this.prjId}&processInstID=${this.processInstId}`
            // 附件信息}`
          },
        // 下一步
        async handleNext() {
            this.refprjBaDetail = this.basicInfo // 基本信息
            this.refbeClDetail = this.Proprietarylist // 竣工决算信息
            // 下一步相关校验
            var doNextCheckFlag = await this.doNextCheck()
            if (!doNextCheckFlag) {
                return false
            }
            // 保存功能
            // saveBtn(2) // 工程档案的没用了
            var nodeNameWord = this.lcList.activityDefID
            if (nodeNameWord === 'info_it_invest_js_02_02' || nodeNameWord === 'info_it_fee_js02') {
                this.$confirm('项目关闭后将无法修改项目的所有信息，您是否确认要关闭项目？', '删除提醒', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    cancelButtonClass: 'pms-zr-button',
                    confirmButtonClass: 'pms-zr-button-primary',
                    type: 'warning'
                }).then(() => {
                    this.workFlowData = {
                      activityInstID: this.lcList.activityInstID,
                      processInstID: this.lcList.processInstID,
                      activityDefID: this.lcList.activityDefID,
                      processDefName: this.lcList.processInstName
                    }
                    this.nextPageVisible = true
                })
            } else {
                this.workFlowData = {
                      activityInstID: this.lcList.activityInstID,
                      processInstID: this.lcList.processInstID,
                      activityDefID: this.lcList.activityDefID,
                      processDefName: this.lcList.processInstName
                    }
                this.nextPageVisible = true
            }
        },
        // 下一步相关校验
        async doNextCheck() {
            //  控制设计变更、销项校验
            const prjId = this.prjId // 目前写死 现在的prjid写死
            const isRevocationAndAdj = await isRevocationAndAdjNew({ prjId: prjId })
            if (isRevocationAndAdj.code !== '200') {
                return false
            }

            // 附件校验
            var fileCheckFlag = await this.fileCheck()
            if (!fileCheckFlag) {
                return false
            }
            // 到货确认
            var goodsArrivedCheckFlag = await this.goodsArrivedCheck(prjId)
            if (!goodsArrivedCheckFlag) {
                return false
            }
            // 结算流程是否完结
            var settlementCheckFlag = await this.settlementCheck(prjId)
            if (!settlementCheckFlag) {
                return false
            }

            // // 费用类不校验转资相关信息  -- it的时候用不上
            // if (this.refprjBaDetail.form.prjType === 'N') {
            //     return true
            // }

            // 是否转资校验
            var MoneyTimeCheckFlag = await this.MoneyTimeCheck()
            if (!MoneyTimeCheckFlag) {
                return false
            }
            // 竣工决算信息校验
            var ifFrom = await this.$refs.projectProprietary.validataForm()
            if (!ifFrom) {
                this.$message({
                    message: '请等待非空数据项回传给PMS。',
                    type: 'warning'
                })
                return false
            }
            return true
        },
        // 下一步确认回调
        nextPageRes(item) {
          const ifNextVal = '1' // 下一步传 1
          this.nextBackPageRes(item, ifNextVal)
        },
        // 退回
        handleBack() {
          this.workFlowData = {
            processInstID: this.lcList.processInstID,
            actInsetId: this.lcList.activityInstID
          }
          this.backPageVisible = true
        },
        // 退回确认回调
        async backPageRes(item) {
          const ifNextVal = '2' // 回退传2
          this.nextBackPageRes(item, ifNextVal)
        },
        // 下一步 && 回退
        async nextBackPageRes(item, ifNextVal) {
          console.log(ifNextVal, 'ifNextVal')
          var workFlowFlag = ''
          var messageVal = ''
          if (ifNextVal === '1') {
            workFlowFlag = 'doNext'
            messageVal = '提交成功'
          } else {
            workFlowFlag = 'doBack'
            messageVal = '回退成功'
          }
          // var getTemplateList = {} // 获取流程场景信息
          // var data = {
          //   prjId: this.prjId,
          //   businessMajor: this.basicList.businessMajor,
          //   prjType: this.basicList.prjType,
          //   prjSubType: this.basicList.secondaryType,
          //   manageMode: this.basicList.manageMode,
          //   wfStage: this.lcList.bizObject.wfStage
          // }
          // const getSceneTempRela = await Axios.getSceneTempRela(data)
          // if (getSceneTempRela.code === '200') {
          //     getTemplateList = getSceneTempRela.data
          // }
          var data = {
              prjId: this.prjId,
              workFlowFlag: workFlowFlag,
              // templateId: getTemplateList.templateId,
              detailId: item.detailId,
              nextNodeId: item.nodeId,
              workItemId: this.urlList.workItemId,
              opinion: item.opinion,
              userIds: item.empId,
              templateId: this.lcList.processDefName,
              nextSceneId: item.sceneId
          }
          const finalNextFlow = await finalNextFlowNew(data)
          if (finalNextFlow.code === '200') {
            this.$message({
                message: messageVal,
                type: 'success'
            })
            this.handleClose()
          }
        },
        // 关闭
        handleClose() {
          clonePage()
        },
        // 到货确认校验
        async goodsArrivedCheck(prjId) {
            var isPushDesign = ''
            // t_prj_list表的is_push值，1代表物资服务已推送给商合系统
            const getIsPush = await getIsPushNew({ prjId: prjId })
            // console.log(getIsPush.code, 'getIsPush.code')
            isPushDesign = getIsPush.data
            if (isPushDesign === '1') {
                const confirmationOfArrival = await confirmationOfArrivalNew({ prjId: prjId, queryType: '6' })
                if (confirmationOfArrival.code !== '200') {
                    return false
                }
            }
            return true
        },

        // 结算流程是否完结
        // IT信息化费用类项目，不进行结算送审，原则上该方法返回值为true
        async settlementCheck(prjId) {
            const isSettleAccountsFinish = await isSettleAccountsFinishNew({ prjId: prjId })
                if (isSettleAccountsFinish.code !== '200') {
                    return false
                }
            return true
        },

        // 是否转资校验
        async MoneyTimeCheck() {
            var forTotalMoney = this.refbeClDetail.forTotalMoney
            var forMoneyTime = this.refbeClDetail.forMoneyTime
            var zanguMoney = this.refbeClDetail.zanguMoney
            var zanguyTime = this.refbeClDetail.zanguTime
            var costAmount = this.refbeClDetail.costAmount
          console.log(this.refbeClDetail, 'this.refbeClDetail')
            // 投资类的需要校验财务是否转资
            // 正式竣工决算时间金额不为空或者暂估时间金额不为空才可进行下一步操作
            var nodeNameWord = this.lcList.activityDefID
            if (nodeNameWord === 'info_it_invest_js_02_01' || nodeNameWord === 'info_it_fee_js01') {
                if (this.MoneyTimeCheckOne(forTotalMoney, forMoneyTime, zanguMoney, zanguyTime) && (costAmount == null || costAmount === '')) {
                    this.$message({
                        message: '财务系统未转资完成，请联系财务系统核实，或点击【获取财务转资信息】按钮，重新获取财务转资结果',
                        type: 'warning',
                        dangerouslyUseHTMLString: true
                    })
                    return false
                }
            }

            return true
        },
        // 2024-10-8 阻断问题if过多解决方案
        MoneyTimeCheckOne(forTotalMoney, forMoneyTime, zanguMoney, zanguyTime) {
          return (forTotalMoney == null || forMoneyTime === '') && (zanguMoney == null || zanguyTime === '')
        },
        // 附件必传上传
        async fileCheck() {
              var fjData = {
                prjId: this.prjId,
                eventType: '1',
                nodeId: this.lcList.activityDefID
              }
              const checkValid = await checkValidNew(fjData)
                if (checkValid.code !== '200') {
                  var docTypeNameVal = []
                  checkValid.data.map(v => {
                    docTypeNameVal.push(v.docTypeName)
                  })
                  this.$message({
                      message: docTypeNameVal.join('、') + ',' + checkValid.message,
                      type: 'warning'
                  })
                  return false
                }
            return true
        }
    }
}
</script>

<style>
.el-collapse {
    margin-bottom: 15px;
}
.el-collapse-item {
    box-shadow: 0px 0px 6px 0px rgba(191, 192, 192, 0.52);
    /* 调整各个item之间的距离为20px */
    /* border: 1px; */
}

.el-collapse-item__wrap {
    padding: 0 20px;
    /* 为el-collapse-item的内容添加20像素的padding */
}

.el-collapse-item__header {
    padding-left: 20px;
    font-size: 14px;
    color: #333333;
    letter-spacing: 0;
    font-weight: 600;
}

.item_icon {
    width: 6px;
    background: rgb(235, 75, 75);
    height: 15px;
    margin-right: 10px;
    border-radius: 10px;
}

::v-deep .content-box {
    width: 100%;
    border-radius: 3px;
    font-size: 12px;
    font-weight: 400;
    line-height: 28px;
}
</style>
